package cn.tedu.rabbitmq.demo.controller;

import cn.tedu.rabbitmq.demo.config.DlxDeclareConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@RestController
public class SendController {
    // 注入一个rabbitTemplate模版对象 构造过程初始化过程 所经历自动配置和redisTemplate一模一样
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @GetMapping("/send")
    public String send(String name) {
        // 组织一个消息数据,发送到声明的组件 demo-ex demo-queue
        String message = "hello:" + name;
        // 底层api发送消息basicPublish("交换机","路由key",properties,body)
        // rabbitmq 可以利用现成方法 实现任何对象序列化和消费反序列化
        // Message<String> message1 = MessageBuilder.withPayload(message).build();
        rabbitTemplate.convertAndSend("demo-fanout","*",message);
        return "发送消息成功！";
    }
    @GetMapping("/send2")
    public String send2(String name) {
        String message = "hello:" + name;
        Message msg = MessageBuilder.withBody(message.getBytes()).setHeader("myHeader","123456").build();
        rabbitTemplate.convertAndSend("demo-direct","key01",msg);
        return "发送消息成功！";
    }
    @GetMapping("/send3")
    public String send3(String name) {
        String message = "hello:" + name;
        Message msg = MessageBuilder.withBody(message.getBytes()).setHeader("myHeader","987456").build();
        rabbitTemplate.convertAndSend("demo-direct","key02",msg);
        return "发送消息成功！";
    }
    @GetMapping("/delay")
    public String delaySend(String name){
        String message = "hello:" + name;
        rabbitTemplate.convertAndSend(DlxDeclareConfig.BIZ_EXCHANGE_NAME,"",message);
        log.info("发送时间:{}", LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
        return "发送消息成功！";
    }
}
